<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import Electrical from "@/components/electrical.vue";
import Space from "@/components/space.vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";
const locale = zhCn;
import request from '@/utils/request'
import { formatDate, getTodayAndYesterday } from '@/utils/utils'
import { ElMessage, ElLoading } from 'element-plus'
defineOptions({
    name: 'HistoricalTrend', // 显式定义组件名
});
const dianqiList = ref([
    {
        name: '电气参数',
        type: 0
    },
    {
        name: '空间参数',
        type: 0
    },
    {
        name: '录波文件',
        type: 0
    },
    {
        name: '健康度',
        type: 0
    }
])


// 获取变电站数据
interface submitObjType {
    zNameId: number;
    gNameIp: Array<object>;
    startTime: string;
    endTime: string;
}
let submitObj: submitObjType = {}

// 获取变电站数据
interface Address {
    id: number;
    miaoshu: string;
    startTime: string;
    zi_addressip_id: number;
}
const gong_value = ref('')
const options = ref<Address[]>([]);
const getSubstation = async () => {
    try {
        const data = await request.get('/media/substation')
        options.value = data.data
    } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '请求失败')
    } finally {
    }
}
// 选中值发生变化时触发
const gongCheng = (res: number) => {
    submitObj.zNameId = res
    getCabinet(res)
}

const openFullScreen2 = () => {
    let loading = ElLoading.service({
        lock: true,
        text: '请求数据中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    setTimeout(() => {
        loading.close()
    }, 1500)

}


// 获取变电柜数据
interface guiType {
    id: number;
    address: string;
    name: string;
    zi_substation_id: number;
}
const gui_value = ref([])
const options2 = ref<guiType[]>([]);
const getCabinet = async (id: number) => {
    gui_value.value = []
    try {
        const data = await request.post('/media/cabinet', { id })
        options2.value = data.data

    } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '请求失败')
    } finally {
    }
}
// 选中值发生变化时触发
const guiCheng = (value: any) => {
    const result = options2.value.filter(item => value.includes(item.id));
    console.log(result)
    submitObj.gNameIp = result
}
// 清空按钮时触发
const guiClear = () => {
    gong_value.value = ''
    gui_value.value = []
}




// 时间选择 
const valueTime = ref('')


// 存储数据到 localStorage
const saveDataToLocalStorage = (data) => {
    localStorage.setItem('myData', JSON.stringify(data))
    localStorage.setItem('myValue', 'me')
}
const commonData = ref({});
const childElectrical = ref(null);
const childSpace = ref(null);
// 查询按钮
const submitGui = async () => {
    if (gong_value.value == '') return ElMessage.error('请选择变电站')
    if (gui_value.value.length == 0) return ElMessage.error('请选择变电柜')
    if (valueTime.value == '' || valueTime.value == null) return ElMessage.error('请选择时间')
    const newTime = valueTime.value.map(res => {
        return formatDate(res)
    })
    submitObj.startTime = newTime[0]
    submitObj.endTime = newTime[1]
    commonData.value = submitObj
    saveDataToLocalStorage(submitObj)

    if (childElectrical.value || childSpace.value) {
        // 假设子组件有一个名为childMethod的方法
        loadingBtn.value = true
        childElectrical.value.childMethod();
        childSpace.value.childMethod();
        // diIndex.value  = 0
    }

}




const diIndex = ref(0)
const dianClick = (index: number) => {
    diIndex.value = index
}

// 变电站下拉框样式调整
const selectOptionWidth = ref()
const setOptionWidth = (event: { srcElement: { offsetWidth: number; }; }) => {
    selectOptionWidth.value = event.srcElement.offsetWidth + 34 + 'px'

}


// 子组件传递父组件
const emit = defineEmits(['getValueMax'])
const transValue = (isZ: boolean) => {
    emit("getValueMax", isZ)
}

// 按钮加载状态
const loadingBtn = ref(false)

const getValueEl = (event: boolean) => {
    loadingBtn.value = event
    transValue(event)

}
const getValue = (event: boolean) => {
    loadingBtn.value = event
    ElMessage.success('查询成功')
}

const selectRef = ref(null); // 获取 el-select 的引用
const customPopperClass = ref('custom-select-popper'); // 自定义下拉框样式类


onMounted(async () => {
    await nextTick()
    await getSubstation()
    await getCabinet(options.value[0].zi_addressip_id)
    // 时间格式转换
    const result = getTodayAndYesterday();
    let newTime = [result.startTime, result.endTime]
    let isoDates = newTime.map(dateStr => {
        let date = new Date(dateStr);  // 转换为 Date 对象
        return date.toISOString();     // 转换为 ISO 格式字符串
    });
    valueTime.value = isoDates

    gong_value.value = options.value[0].name
    gui_value.value = [options2.value.slice(0, 1)[0].name]

    submitObj.startTime = result.startTime
    submitObj.endTime = result.endTime
    submitObj.zNameId = options.value[0].zi_addressip_id
    submitObj.gNameIp = [options2.value[0]]
    saveDataToLocalStorage(submitObj)
    openFullScreen2()
    await submitGui()
})

</script>

<template>
    <div class="h-max">
        <div class="selectKua">
            <!-- clearable -->
            <el-select v-model="gong_value" placeholder="请选择变电站" @focus="setOptionWidth" style="width: 200px"
                @change="gongCheng" @clear="guiClear">
                <el-option :style="{ width: selectOptionWidth }" v-for="item in options" :key="item.zi_addressip_id"
                    :label="item.name" :value="item.zi_addressip_id" />
            </el-select>

            <el-select v-model="gui_value" placeholder="请选择柜号" multiple collapse-tags  @focus="setOptionWidth" :popper-class="customPopperClass"   :popper-append-to-body="false"
                :disabled="gong_value == '' ? true : false"  @change="guiCheng"
                style="width: 200px; margin-left: 20px;margin-right: 20px;">
                <!-- :style="{ width: selectOptionWidth }" -->
                <el-option v-for="item in options2" :key="item.address" :label="item.name" :value="item.id" :style="{ width: selectOptionWidth }">
                    <!-- 自定义选项内容 -->
                    <div class="checkBoxq" style="width: 100%; display: flex; align-items: center; justify-content: space-between;">
                        <span>{{ item.name }}</span>
                        <el-checkbox v-model="gui_value" :value="item.id" />
                    </div>
                </el-option>
            </el-select>

            <el-config-provider :locale="locale">
                <el-date-picker v-model="valueTime" type="daterange" range-separator="To" start-placeholder="开始时间"
                    end-placeholder="结束时间" size="default" />
            </el-config-provider>


            <el-button type="primary" :loading="loadingBtn" style="margin-left: 20px;" @click="submitGui">{{ loadingBtn
                ? '查询中' : '查询' }} </el-button>
        </div>
        <div class="h-max-top">
            <div class="h-max-top-item" :class="diIndex == index ? 'boeff4' : ''" v-for="(item, index) in dianqiList"
                :key="index" @click="dianClick(index)">{{ item.name }}</div>
        </div>
        <div class="h-max-bom" v-show="diIndex == 0">
            <Electrical :commonData="commonData" ref="childElectrical" @getValue="getValue" />
        </div>
        <div class="h-max-bom" v-show="diIndex == 1">
            <!--  @getValue="getValue"  -->
            <Space ref="childSpace" />
        </div>
    </div>
</template>

<style scoped lang="scss">
.h-max {
    width: 100%;
    height: 100%;
    position: relative;

    .selectKua {
        position: absolute;
        left: 860px;
        top: -50px;
        height: 50px;
    }

    .h-max-top {
        display: flex;
        height: 48px;
        border: 2px solid #2d2d2d;

        // box-sizing: border-box;
        .h-max-top-item {
            width: 440px;
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 18px;
            color: #ffffff;
            box-sizing: border-box;
            cursor: pointer;
            border-bottom: 2px solid transparent;

        }
    }

    .h-max-bom {
        // background-color: #98b8d7;
        width: 100%;
        height: 890px;
        overflow-y: scroll;

    }
}

.boeff4 {
    border-bottom: 2px solid #097ff4 !important;
    color: #097ff4 !important;
    font-weight: bold;
}

/* 自定义滚动条的样式 */
.h-max-bom::-webkit-scrollbar {
    width: 0px;
    /* 设置滚动条的宽度 */
}

.h-max-bom::-webkit-scrollbar-thumb {
    background-color: darkgrey;
    /* 设置滚动条的颜色 */
    border-radius: 10px;
    /* 设置滚动条圆角 */
}

.h-max-bom::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 设置滚动条轨道的背景颜色 */
}


/* 自定义选项样式 */
:deep(.el-select-dropdown__item) {
    padding: 0 !important;
    /* 去除默认内边距 */
}

:deep(.el-select-dropdown__item .el-checkbox) {
    margin-right: 0;
    /* 去除 Checkbox 的右边距 */
}
// :deep(.el-select-dropdown__item.is-selected) {
//     color: #000000 !important;
// }
// /* 隐藏对钩图标 */
// :deep(.el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected:after) {
//   right: 0 !important;
//   top: 0 !important;
// }

// 多选框√去掉
.el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected::after {
  display: none !important;
}
.el-select-dropdown__item{
    padding: 0 0px 0 20px !important;

}
.el-select-dropdown__item.is-selected {
  color: #303133;
  font-weight: 400;
}
.el-select-dropdown__item {
  color: #303133;
}
.checkBoxq{
    :deep(.el-checkbox__input.is-checked) .el-checkbox__inner{
    background-color: #383535 !important;
}
}

// :deep(.el-select-dropdown__item){
//     padding: 0 0px 0 20px !important;

// }
</style>
